package com.open.capacity.salary.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.salary.dto.GridHeadDataDto;
import com.open.capacity.salary.dto.GridHeadDataDto2;
import com.open.capacity.salary.entity.GzItem;
import com.open.capacity.salary.entity.GzZt;
import com.open.capacity.salary.service.*;
import com.open.capacity.utils.StringUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 银行代发
 *
 * @author
 * @email
 * @date 2021-08-02 14:26:51
 */
@Slf4j
@RestController
@RequestMapping("gzbankautos")
@Api(tags = "工资报表")
public class GzBankAutoController {

    @Autowired
    private GzBankAutoService bankAutoService;

    @Autowired
    private GzItemService gzItemService;

    @Autowired
    private GzZtService ztService;

    @Autowired
    private GzEnableMonthService gzEnableMonthService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public PageResult list(@RequestParam Map<String, Object> params) {
        params.put("limit", 1500);
        PageResult pageResult = bankAutoService.pageAll(params);
        return pageResult;
    }


    /**
     * 工资查询导出
     *
     * @return
     */
    @GetMapping("/exportExcel")
    public void export(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        String companyId = params.get("companyId").toString();
        String ztId = params.get("ztId").toString();
        String columnName = params.get("columns").toString();
        String ztName = ztService.findNameByIds(ztId);

        if (ztId.contains(",")) {
            ztId = ztId.split(",")[0];
        }
        //账套当前月份
        String currentMonth = gzEnableMonthService.findByZtId(companyId, ztId).getCurrentMonth();
        String day = currentMonth.substring(0, 4) + "年" + currentMonth.substring(5, 7) + "月";
        String fileName = ztName + "(" + day + ")_" + columnName;

        List<Map<String, Object>> resList = bankAutoService.findAll(params);
        if (CollectionUtils.isNotEmpty(resList)) {
            for (int i = 0; i < resList.size(); i++) {
                boolean existsItem = false;
                for (Map.Entry<String, Object> entry : resList.get(i).entrySet()) {
                    if (entry.getKey().equals("money")) {
                        existsItem = true;
                        if (entry.getValue() == null || new BigDecimal(entry.getValue().toString()).compareTo(BigDecimal.ZERO) == 0) {
                            resList.remove(i);
                            i--;
                            break;
                        }
                    }
                }
                if(!existsItem) {
                    resList.remove(i);
                    i--;
                }
            }
        }
        //封装表头
        List<ExcelExportEntity> headList = new ArrayList<>();
        ExcelExportEntity excelExportEntity;

        /**
         * name : "姓名"    ---> 表头显示    key是属性映射（后面会用到，key任意配置，但不要在同一个方法中重复）
         * excelExportEntity.setWidth(30);    --->  设置单元格宽度
         * excelExportEntity.setNeedMerge(true);   --->  开启单元格合并，这个属性的开启并不会产生影响，因为没有配置合并条件
         * */


        excelExportEntity = new ExcelExportEntity("员工编号", "usercode");
        excelExportEntity.setWidth(10);
        excelExportEntity.setNeedMerge(true);
        headList.add(excelExportEntity);

        excelExportEntity = new ExcelExportEntity("姓名", "username");
        excelExportEntity.setWidth(12);
        excelExportEntity.setNeedMerge(true);
        headList.add(excelExportEntity);

        excelExportEntity = new ExcelExportEntity("银行账号", "bankaccount");
        excelExportEntity.setWidth(20);
        excelExportEntity.setNeedMerge(true);
        headList.add(excelExportEntity);

        excelExportEntity = new ExcelExportEntity("金额", "money");
        excelExportEntity.setWidth(12);
        excelExportEntity.setNeedMerge(false);
        excelExportEntity.setType(10);
        headList.add(excelExportEntity);

        //"封装"数据
        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, Object> dataMap;
        //循环封装数据
        for (Map<String, Object> element : resList) {
            dataMap = new HashMap<>();
            dataMap.put("departmentname", element.get("departmentname"));
            dataMap.put("usercode", element.get("usercode"));
            dataMap.put("username", element.get("username"));
            dataMap.put("bankaccount", element.get("bankaccount"));
            dataMap.put("money", element.get("money"));
            dataList.add(dataMap);
        }
        //导出
        if (CollectionUtils.isNotEmpty(dataList)) {
            response.setContentType("application/vnd.ms-excel");
            try {
                response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls");
            } catch (UnsupportedEncodingException e) {
                log.error(e.toString());
            }
            OutputStream ouputStream = null;
            ExportParams param = new ExportParams("银行代发工资（" + day + ")", currentMonth + columnName);
            Workbook workbook = ExcelExportUtil.exportExcel(param, headList, dataList);
            try {
                ouputStream = response.getOutputStream();
                workbook.write(ouputStream);
            } catch (Exception e) {
                log.error(e.toString());
                throw new RuntimeException("系统异常");
            } finally {
                try {
                    if (ouputStream != null) {
                        ouputStream.flush();
                        ouputStream.close();
                    }
                } catch (Exception e) {
                    log.error(e.toString());
                    throw new RuntimeException("系统异常");
                }
            }
        }
    }

}
